package com.mrx.xfriendship.service;

import com.alibaba.fastjson.JSONObject;
import com.mrx.commons.annotations.XLog;
import com.mrx.xfriendship.dao.SystemInfoMapper;
import com.mrx.xfriendship.model.dto.SystemInfoDTO;
import com.mrx.xfriendship.model.vo.SystemManagerVO;
import com.mrx.xfriendship.model.vo.UpdateSystemInfoVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author : 肖康宁
 * @since : 2023-01-28 10:34
 **/
@XLog
@Service
@DubboService
public class SystemInfoServiceImpl implements ISystemInfoService {

    @Resource
    private SystemInfoMapper systemInfoMapper;

    private static final Logger logger = LoggerFactory.getLogger(SystemInfoServiceImpl.class);

    @Override
    public void setSystemInfo(SystemInfoDTO systemInfo) {
        SystemInfoDTO infoInDB = getSystemInfoByKey(systemInfo.getKey());
        if (infoInDB != null) {
            JSONObject json = systemInfo.getJSONValue();
            infoInDB.getJSONValue().forEach((k, v) ->
                    json.merge(k, v, (o, n) -> Integer.parseInt(o + "") + Integer.parseInt(n + ""))
            );
            systemInfo.setValue(json.toJSONString());
            logger.debug("SystemInfo: {}", systemInfo);
            systemInfoMapper.updateByKey(systemInfo);
        } else {
            systemInfoMapper.insert(systemInfo);
        }

    }

    @Override
    public SystemInfoDTO getSystemInfo(SystemInfoDTO systemInfo) {
        return systemInfoMapper.selectSelective(systemInfo);
    }

    @Override
    public SystemInfoDTO getSystemInfoByKey(String key) {
        SystemInfoDTO dto = new SystemInfoDTO();
        dto.setKey(key);
        return systemInfoMapper.selectSelective(dto);
    }

    @Override
    public List<SystemInfoDTO> listSystemInfo(SystemManagerVO vo) {
        // TODO: 2023-03-19 上午 9:40:36 增加 configAble 字段
        vo.setName("headPic");
        return systemInfoMapper.selectList(vo);
    }

    @Override
    public void updateSystemInfo(UpdateSystemInfoVO vo) {
        SystemInfoDTO info = new SystemInfoDTO();
        info.setKey(vo.getName());
        info.setValue(vo.getValue());
        systemInfoMapper.updateByKey(info);
    }

}
